package com.example.demo.controller;

import com.example.demo.entity.GoodEntity;
import com.example.demo.entity.Inquire;
import com.example.demo.entity.QGoodEntity;
import com.example.demo.jpa.GoodJpa;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * Created by malin on 2017/7/8.
 */
@RestController
public class QueryController {
    @Autowired
    private GoodJpa goodJpa;

    //注入EntityManager对象
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * querysdl单独查询
     * @return
     */
    @RequestMapping(value = "/query")
    public List<GoodEntity> list() {

        //querydsl查询实体
        QGoodEntity _good=QGoodEntity.goodEntity;

        //构建JPA查询对象
        JPAQuery<GoodEntity> jpaQuery=new JPAQuery<>(entityManager);

        //返回查询接口
        return jpaQuery
                .select(_good)
                .from(_good)
                .where(_good.type.id.eq(Long.valueOf("1")))
                .fetch();

    }

    /**
     * @return
     */
    @RequestMapping(value = "/join")
    public List<GoodEntity> join(){

        //querysdl查询实体
        QGoodEntity _good=QGoodEntity.goodEntity;


        //查询条件
        BooleanExpression expression=_good.type.id.eq(Long.valueOf("1"));


        //执行查询
        Iterator<GoodEntity>  iterator=goodJpa.findAll(expression).iterator();

        List<GoodEntity> goods=new ArrayList<>();

        if(iterator.hasNext()){
            goods.add(iterator.next());
        }

        return goods;



    }

    /**
     * 优化的查询方法
     * @return
     */
    @RequestMapping(value = "/join2")
    public List<GoodEntity> join2(){

        //querysdl查询实体
        QGoodEntity _good=QGoodEntity.goodEntity;

        Inquire inquire=new Inquire();
        inquire.addExpression(_good.type.id.eq(Long.valueOf("1")));
        return inquire.iteratorToList(goodJpa.findAll(inquire.buildQuery()));




    }
}
